(function () {
    var exports = this;

    var $ = null;

    var HUTYPE_LIUJU = 0;
    var HUTYPE_ZIMO = 1;
    var HUTYPE_DIANPAO = 2;
    var HUTYPE_JIESAN = 3;

    var JiesuanLayer = cc.Layer.extend({
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
        },
        ctor: function (data) {
            this._super();

            var that = this;

            var scene = loadNodeCCS(res.JiesuanLayer_json, that);
            // this.addChild(scene.node);
            $ = create$(this.getChildByName("Scene"));

            var isZimo = (data['hu_type'] == HUTYPE_ZIMO);
            var isLiuju = (data['hu_type'] == HUTYPE_LIUJU);
            var isDianpao = (data['hu_type'] == HUTYPE_DIANPAO);
            var isJieSan = (data['hu_type'] == HUTYPE_JIESAN);
            var zhuangUid = data['zhuang'];
            var dianpaoUid = data['dianpao_uid'];
            var huPaiId = data['hu_pai_id'];

            var btnFenxiang = $('root.panel.btn_fenxiang');
            var btnStart = $('root.panel.btn_start');
            var btnChakan = $('root.panel.btn_chakan');

            // if (gameData.loginType == 'yk') {
            //     btnFenxiang.setVisible(false);
            //     btnStart.setPositionX(btnStart.getParent().getContentSize().width / 2);
            //     btnChakan.setPositionX(btnChakan.getParent().getContentSize().width / 2);
            // }

            var players = data.players;

            var huCnt = 0;
            var diangangMap = {};
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var isHu = player['hu'];
                if (isHu) {
                    huCnt += 1;
                }

                var duiArr = player['dui_arr'];
                for (var j = 0; j < duiArr.length; j++) {
                    var dui = duiArr[j];
                    if (dui['from_uid'] && dui['from_uid'] != player.uid) {
                        diangangMap[dui['from_uid']] = diangangMap[dui['from_uid']] || 0;
                        diangangMap[dui['from_uid']]++;
                    }
                }
            }

            var my_score = 0;

            var set_outline_status = function (text, score) {
                if (score < 0) {
                    // console.log('disableeffect');
                    text.disableEffect();
                } else {
                    text.enableOutline(cc.color(226, 88, 0), 2);
                }
            };

            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var uid = player['uid'];
                var score = player['score'];
                var gangScore = player['gang_score'];
                var fan = player['fan'];
                var paiArr = player['pai_arr'];
                var dingArr = player['dingArr'];
                var duiArr = player['dui_arr'];
                var textArr = player['text_arr'];
                var isHu = player['hu'];
                var hupaiId = player['hupaiId'];

                var paiIdArr = [];

                if ($('root.panel.row' + i))
                    $('root.panel.row' + i).setVisible(true);
                    // continue;

                if (isHu) {
                    var idx = paiArr.indexOf(huPaiId);
                    if (idx >= 0) {
                        paiArr.splice(idx, 1);
                    }
                }

                var gouchengArr = [];

                var playerInfo = gameData.getPlayerInfoByUid(uid);
                $('root.panel.row' + i + '.lb_nickname').setString(ellipsisStr(playerInfo.nickname, 5));
                $('root.panel.row' + i + '.sp_zhuang').setVisible(zhuangUid == uid);
                $('root.panel.row' + i + '.bg').setVisible(gameData.uid != uid);
                $('root.panel.row' + i + '.bg_self').setVisible(gameData.uid == uid);
                loadImageToSprite(playerInfo.headimgurl, $('root.panel.row' + i + '.head'),true);
                // loadImage(playerInfo.headimgurl, $('root.panel.row' + i + '.head'), false);
                if (isDianpao) {
                    if(uid == dianpaoUid)
                        $('root.panel.row' + i + '.dianpao').setVisible(true);
                    else if(isHu)
                        $('root.panel.row' + i + '.hu').setVisible(true);
                } else if (isHu && isZimo) {
                    $('root.panel.row' + i + '.zimo').setVisible(true);
                } else if (isJieSan && isHu){
                    // $('root.panel.row' + i + '.hu').setVisible(true);
                }

                if(gameData.mapId == MAP_ID_SICHUAN_XUEZHAN || gameData.mapId == MAP_ID_SICHUAN_XUELIU){
                    $('root.panel.row' + i + '.hu').setVisible(false);
                }

                $('root.panel.row' + i + '.lb_score').setString(fan <= 0 ? fan : ('+' + fan.toString()));
                // set_outline_status($('root.panel.row' + i + '.lb_score'), fan);
                $('root.panel.row' + i + '.lb_score_gang').setString(gangScore <= 0 ? gangScore : ('+' + gangScore.toString()));
                // set_outline_status($('root.panel.row' + i + '.lb_score_gang'), gangScore);
                $('root.panel.row' + i + '.lb_score_sum').setString(score <= 0 ? score : ('+' + score.toString()));
                // set_outline_status($('root.panel.row' + i + '.lb_score_sum'), score);
                if (uid == gameData.uid) my_score = score;

                while (true) {
                    for (var j = 0; j < duiArr.length; j++) {
                        var dui = duiArr[j];
                        if (dui.type == 5)
                            break;
                    }
                    if (j == duiArr.length)
                        break;
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    duiArr.splice(j, 1);
                }

                _.remove(paiArr, function (n) {
                    return n == 0;
                });

                paiArr.sort(function (a, b) {
                    return a - b
                });
                var _laizi_arr = [];
                if (data.laizi && data.laizi >= 0) {
                    _laizi_arr.push(data.laizi);
                }
                if (data.laizi2 && data.laizi2 >= 0) {
                    _laizi_arr.push(data.laizi2);
                }
                // if (gameData.mapId == MAP_ID_HONGZHONG || gameData.mapId == MAP_ID_FEIXI) {
                //     _laizi_arr.push(32);
                // }
                if (_laizi_arr.length > 0) {
                    for (var j = 0; j < _laizi_arr.length; j++) {
                        var oldSize = paiArr.length;
                        _.pull(paiArr, _laizi_arr[j]);
                        if (paiArr.length != oldSize) {
                            var t = paiArr.length;
                            for (var k = 0; k < oldSize - t; k++)
                                paiArr.splice(0, 0, _laizi_arr[j]);
                        }
                    }
                }
                duiArr.sort(function (a, b) {
                    if (a['pai_arr'][0] == b['pai_arr'][0]) {
                        if (a['pai_arr'][1] == b['pai_arr'][1])
                            return a['pai_arr'][2] - b['pai_arr'][2];
                        return a['pai_arr'][1] - b['pai_arr'][1];
                    }
                    return a['pai_arr'][0] - b['pai_arr'][0];
                });

                var a0 = $('root.panel.row' + i + '.a' + 0);
                //a0.setScale(0.8);
                var anGangCnt = 0;
                var gangCnt = 0;
                for (var j = 0; j < duiArr.length; j++) {
                    var dui = duiArr[j];
                    if (dui.type == 1 || dui.type == 2) {
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][1]);
                        paiIdArr.push(dui['pai_arr'][2]);
                    }
                    if (dui.type == 3) {
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        gangCnt++;
                    }
                    if (dui.type == 4) {
                        paiIdArr.push(0);
                        paiIdArr.push(0);
                        paiIdArr.push(0);
                        paiIdArr.push(dui['pai_arr'][0]);
                        anGangCnt++;
                    }
                    paiIdArr.push(-1);
                }

                if (anGangCnt)
                    gouchengArr.push("暗杠" + (anGangCnt > 1 ? 'x' + anGangCnt : ''));

                if (gangCnt)
                    gouchengArr.push("明杠" + (gangCnt > 1 ? 'x' + gangCnt : ''));

                if (diangangMap[uid])
                    gouchengArr.push("点杠" + (diangangMap[uid] > 1 ? 'x' + diangangMap[uid] : ''));

                for (var j = 0; j < paiArr.length; j++) {
                    paiIdArr.push(paiArr[j]);
                }

                if(hupaiId == undefined){
                    //排除血战的其他情况
                    if (isHu && huPaiId) {
                        if (paiIdArr[paiIdArr.length - 1] != -1)
                            paiIdArr.push(-1);
                        paiIdArr.push(huPaiId);

                        gouchengArr.push(isZimo ? '自摸' : '点炮胡');
                    }
                }else{
                    // 血战
                    if(isHu && hupaiId && hupaiId!= 0 ){
                        paiIdArr.push(-1);
                        paiIdArr.push(hupaiId);
                        gouchengArr.push(isZimo ? '自摸' : '点炮胡');
                    }
                }

                if (uid == dianpaoUid) {
                    gouchengArr.push('点炮' + (huCnt > 1 ? 'x' + huCnt : ''));
                }

                if (textArr) {
                    gouchengArr = [];
                    for (var j = 0; j < textArr.length; j++) {
                        var obj = textArr[j];
                        for (var key in obj) {
                            if (obj.hasOwnProperty(key)) {
                                gouchengArr.push(decodeURIComponent(key) + (obj[key] > 1 ? 'x' + obj[key] : ''));
                            }
                        }
                    }
                }
                $('root.panel.row' + i + '.lb_goucheng').setString(gouchengArr.join(" "));

                var gapNum = 0;
                var gapDistance = 10;
                for (var j = 0; j < paiIdArr.length; j++) {
                    if (paiIdArr[j] == -1) {
                        gapNum++;
                        continue;
                    }
                    var pai = $('root.panel.row' + i + '.a' + j);
                    if (!pai) {
                        pai = duplicateNode(a0);
                        pai.setPositionX(a0.getPositionX() + a0.getContentSize().width * a0.getScaleX() * (j - gapNum) + gapNum * gapDistance);
                        a0.getParent().addChild(pai);
                    }

                    var paiName = 'p2s' + paiIdArr[j] + '.png';
                    var lb = pai.getChildByName('lb_lai');
                    if (_laizi_arr.indexOf(paiIdArr[j]) >= 0) {
                        if (!lb) {
                            lb = new cc.Sprite('res/table/lb_lai.png');
                            lb.setName('lb_lai');
                            pai.addChild(lb);
                            lb.setPosition(17.1, 21.5);
                        }
                        lb.setVisible(true);
                    } else {
                        if (lb) {
                            lb.setVisible(false);
                        }
                    }
                    setSpriteFrameByName(pai, paiName, 'pai');
                    var lb = pai.getChildByName('lb');
                    if (lb) {
                        lb.setVisible(false);
                    }
                    if (player.uid == gameData.uid) {
                        myTotalScore = player.score;
                        $('root.panel.row' + i + '.bg').setVisible(true);
                    }
                }
            }
            if(isJieSan){
                $('root.panel.title_jiesan').setVisible(true);
                $('root.panel.title_jiesan.title_jiesan').setVisible(true);
            } else if (isLiuju) {
                $('root.panel.title_jiesan').setVisible(true);
                $('root.panel.title_jiesan.title_liuju').setVisible(true);
            } else if (my_score > 0) {
                $('root.panel.title_win_bg').setVisible(true);
            } else {
                $('root.panel.title_fail_bg').setVisible(true);
                $('root.panel.title_fail_bg.title_zjzl').setVisible(true);
            }
            $('root.panel.lb_ts').setString(timestamp2time(data['ts']));
            $('root.panel.lb_roomid').setString('房号: ' + gameData.roomId );
            $('root.panel.lb_jushu').setString('局数: ' + data['cur_round'] + '/' + data['total_round']);
            $('root.panel.lb_wanfa').setString(gameData.wanfaDesp);
            $('root.panel.lb_wanfatitle').setString('玩法:'+mapId2Name(gameData.mapId));
            for (var i = players.length; i < 4; i++)
                $('root.panel.row' + i).setVisible(false);

            TouchUtil.setOnclickListener(btnFenxiang, function () {
                ShareUtil.SharePic(that);
            });

            TouchUtil.setOnclickListener(btnStart, function () {
                // ready
                network.send(3004, {room_id: gameData.roomId});
                window.maLayer.onJiesuanClose(true);
                that.removeFromParent(true);
            });

            var closeFunc = function () {
                // ready
                window.maLayer.onJiesuanClose(false);
                that.removeFromParent(true);
            };
            TouchUtil.setOnclickListener(btnChakan, closeFunc);

            if (data['is_last']) {
                btnStart.setVisible(false);
                btnChakan.setVisible(true);
            }

            if (gameData.mapId == MAP_ID_ZHUANZHUAN
                || gameData.mapId == MAP_ID_CHANGSHA
                || gameData.mapId == MAP_ID_PINGXIANG258
                || gameData.mapId == MAP_ID_GUANGDONG_TUIDAO
                || gameData.mapId == MAP_ID_GUANGDONG_JIPING
                || gameData.mapId == MAP_ID_SHANXI_ZHUANZHUAN
            ) {
                var paiArr = data['zhongma_pai_arr'] || [];
                if (paiArr.length) {
                    var zhong_idx = [];
                    var zhongma_id = data['zhong_arr'] || [];
                    for (var i = 0; i < zhongma_id.length; i++) {
                        for (var j = 0; j < paiArr.length; j++) {
                            if (zhongma_id[i] == paiArr[j] && zhong_idx.indexOf(j) < 0) {
                                zhong_idx.push(j);
                                break;
                            }
                        }
                    }
                    for (var i = 0; i < Math.min(paiArr.length, 6); i++) {
                        var pai = $('root.panel.ma.a' + i);
                        var paiName = 'p2s' + paiArr[i] + '.png';
                        setSpriteFrameByName(pai, paiName, 'pai');
                        if (zhong_idx.indexOf(i) < 0) {
                            Filter.grayMask(pai);
                        }
                    }
                    for (; i < 6; i++) {
                        var pai = $('root.panel.ma.a' + i);
                        pai && pai.setVisible(false);
                    }

                    $('root.panel.ma').setVisible(true);
                }
            }

            return true;
        }
    });

    exports.JiesuanLayer = JiesuanLayer;
})(window);
